package org.indp.mongowl.ui;

import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.vaadin.data.Item;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;

import java.util.List;

/**
 *
 */
public class QueryControllerComponent extends HorizontalLayout {

    public static final String OBJECT = "OBJECT";
//    public static final String ID = "ID";

    private final int limit = 30;
    private int offset = 0;

    public QueryControllerComponent(final DBCollection collection, final Table table) {
        table.setContainerDataSource(new IndexedContainer());
//        table.addContainerProperty(ID, String.class, "", "_id", null, Table.Align.LEFT);
        table.addContainerProperty(OBJECT, String.class, "", "Content", null, Table.Align.LEFT);

        setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);
        setSpacing(true);
        addComponent(new Label(collection.getName() + ", " + collection.getCount() + " item(s)"));
        addComponent(new Button("Next " + limit, new Button.ClickListener() {
            @Override
            public void buttonClick(Button.ClickEvent event) {
                fillTable(collection, table);
            }
        }));

        fillTable(collection, table);
    }

    private void fillTable(DBCollection collection, Table table) {
        // todo
        if (collection.count() <= offset) {
            return;
        }
        List<DBObject> objects = collection.find().skip(offset).limit(limit).toArray();
        if (objects != null && !objects.isEmpty()) {
            table.removeAllItems();
            for (DBObject object : objects) {
                Item item = table.addItem(object);
                item.getItemProperty(OBJECT).setValue(object.toString());
            }
        }
        offset += limit;
    }
}
